package com.hliushi.oauth2.config;

import com.hliushi.oauth2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 授权服务器配置
 *
 * @author llhuang10
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;


    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;


    /**
     * 在 JWT 编码的令牌值和 OAuth 身份验证信息（双向）之间进行转换的助手。 在授予令牌时也充当TokenEnhancer
     */
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    // @Autowired
    // @Qualifier("redisTokenStore")
    // private TokenStore tokenStore;

    /*
     * 使用密码模式所需配置
     *
     * @param endpoints 端点配置器
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 配置JWT内容增强器
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates);

        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService)
                // 配置存储令牌策略
                .tokenStore(tokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(enhancerChain);
        // tokenStore() 这个方法是private, 没有访问权限
        // 'tokenStore()' has private access in '....AuthorizationServerEndpointsConfigurer'
        // public AuthorizationServerEndpointsConfigurer tokenStore(TokenStore tokenStore)
        // .tokenStore(tokenStore);
    }

    /**
     * 授权服务器的配置
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // 配置client-id
                .withClient("admin")
                // 配置client-secret
                .secret(passwordEncoder.encode("112233"))
                // 配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                // 配置舒心Token的有效期
                .refreshTokenValiditySeconds(864000)
                // 配置redirect_uri, 用于授权成功后跳转 (可选)
                .redirectUris("http://localhost:8081/login")
                // 自动授权配置
                .autoApprove(true)
                // 配置申请的权限范围
                .scopes("all")
                // 配置grant_type, 表示授权类型 [authorization_code 授权码模式]
                //              [password 密码模式]
                // public ClientBuilder authorizedGrantTypes(String... authorizedGrantTypes)
                // 这里参数是一个可变长度的参数列表, 所以可以填写多个参数, 这里表示多种授权模式可以同时存在
                .authorizedGrantTypes("password", "refresh_token", "authorization_code");
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 获取秘钥需要身份认证, 使用单点登录是必须配置
        /**
         * bug点,  写错单词 写成了isAuthentication
         * 正确的单词是 isAuthenticated
         */
        security.tokenKeyAccess("isAuthenticated()");
    }
}
